package cn.gqr.controller;

import cn.gqr.entity.Book;
import cn.gqr.entity.Largefile;
import cn.gqr.entity.Type;
import cn.gqr.service.BookService;
import cn.gqr.service.TypeService;
import cn.gqr.tool.RespJson;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
public class ProductController {


    @Autowired
    private BookService bookservice;

    @Autowired
    private TypeService typeservice;


    //分页查询全部书本信息
    //根据typeId查询,如果为null则无条件查询
    //key(放数据库字段名称销量,点赞,加入购物车) null不需要排序，不等于null 对key值字段排序
    @RequestMapping("/public/selectBookByPage/{start}/{num}")
    public Map<String,Object> selectBookByPage(@PathVariable("start")int start,@PathVariable("num")int num, Integer typeId) {
        Map map = bookservice.selectBookByPage(start, num, typeId, null);
        return RespJson.pack(200,"书本信息",map);
    }

    //根据书本名称的模糊查询并且分页
    @RequestMapping("/public/selectBookByNamePage/{start}/{num}")
    public Map<String,Object> selectBookByNamePage(@PathVariable("start")int start,@PathVariable("num")int num, String name) {

        if(name!=null && !"".equals(name)){

            Map map = bookservice.selectBookByNamePage(start, num, name);

            return RespJson.pack(200,"名称模糊查找",map);
        }

        return RespJson.pack(200,"搜索关键字为空或者不能小于2",null);
    }


    //获取点赞或者销量或者加入购物车前五的书本对象
    @GetMapping(value = {"/public/selectRate5","/public/selectFavnum5","/public/selectSalenum5"})
    public Map<String, Object> selectData5(HttpServletRequest request) {

        String uri = request.getRequestURI();

        if("/api/public/selectRate5".equals(uri)){
            return RespJson.pack(200,"点赞前五书本信息",bookservice.selectData5("rate"));
        }

        if("/api/public/selectFavnum5".equals(uri)){
            return RespJson.pack(200,"销量前五书本信息",bookservice.selectData5("favnum"));
        }

        return RespJson.pack(200,"加入购物车前五书本信息",bookservice.selectData5("salenum"));
    }

    //根据id获取图片对象
    @RequestMapping(value = "/public/showImg/{id}",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] showPictureById(@PathVariable("id") String id) {

        Largefile largefile = bookservice.showPictureById(id);

        if(largefile == null){
            log.info("无id为{}的图片信息",largefile.getId());

            return null;
        }

        return (byte[])largefile.getContent();
    }


    //类型的全查询
    @RequestMapping("/public/findTypeAll")
    public Map<String,Object> selectTypeAll(){
        List<Type> types = typeservice.selectTypes();
        return RespJson.pack(200,"所有类型信息",types);
    }


}
